<?php
$host = "192.168.1.100";
$host = "localhost";
$port = 8000;

$key = "serverkey";
$uid = uniqid("php");
$nickname = $uid;

chat_stat();

function chat_stat()
{
	global $host, $port, $key, $nickname,$uid;

	$fp = fsockopen($host, $port, $errno, $errstr, 1);
	if (!$fp) {
		echo "$errstr ($errno)\n";
		exit;
	} else {
		$login_pack = s(100) . str($key) .str($uid) . str($nickname);

		//len+type+uid+time
		$uid = "uid_2";
		$dis_pack = s(116) . str($uid) . i(100);

		write_pack($fp, $login_pack , $dis_pack);

		$pack_len = 0;
		while($result = wait_pack($fp)){
			$pack_len++;

			if ($result['type'] == 117){
				echo $result['ret']['str'] . "\r\n";
				break;
			}
		}
		fclose($fp);
	}
}

function write_pack($fp, $str)
{
	$num=func_num_args(); 
	$list=func_get_args(); 

	$wstr = "";
	for($i = 1; $i < $num; $i++)
	{
		$pack_len = strlen($list[$i]);
		$wstr .= i($pack_len) . $list[$i];
	}
	if (@fwrite($fp, $wstr) === false){
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		exit("fwrite fail! code:$errorcode error:$errormsg\n");
	}
}
function wait_pack($fp)
{
	$data = @fread($fp, 4);
	if (strlen($data) == 0){
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		exit("fread is 0 closed code:$errorcode, error:$errormsg\n");
	}

	$len = current(unpack("i", $data));
	$type = current(unpack("s", fread($fp, 2)));
	
	if ($len > 2)
		$data = fread($fp, $len - 2);
	$ret = array();

	if ($type == 101){
		$ret['status'] = current(unpack("i", $data));
	}elseif($type == 5){
		$ret['errortype'] = current(unpack("i", $data));
	}elseif($type == 115){
		$ret['sub_type'] = current(unpack("i", $data));
		$str_len = current(unpack("i", substr($data, 4)));
		$ret['str'] = current(unpack("a*", substr($data, 8)));
	}

	return array("len" => $len, "type" => $type,'ret' => $ret);
}

// 封装字符串
function str($str)
{
	if ($str == NULL)
		return "";
	else
		return pack("i",strlen($str)) .   $str;
}

// 封装int
function i($i)
{
	return pack("i", $i);
}

// 封装short
function s($s)
{
	return pack("s", $s);
}
